//
//  CRSpaceViewController.m
//  CRChatRoom
//
//  Created by lanou3g on 15/11/21.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRSpaceViewController.h"
#import "CRSpaceCell.h"
#import "CRSpaceFrame.h"
#import "CRSpaceHeadView.h"
#import "CRTool.h"
#import "CRSpace.h"
#import "CRWriteViewController.h"
#import "MJRefresh.h"
#import "CRCellBottomView.h"
#import "CRSpaceCommentViewController.h"
#import "CRDataTool.h"
#import "MBProgressHUD+MJ.h"

@interface CRSpaceViewController () <UITextFieldDelegate, CRSpaceHeadViewDelegate>

// 存放模型的数组
@property (nonatomic, strong) NSArray *spaceFrames;

@end

@implementation CRSpaceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 注册cell
    [self.tableView registerClass:[CRSpaceCell class] forCellReuseIdentifier:@"cell"];

    // 添加刷新控件
    [self addRefresh];
    
    // 进入刷新
//    [self.tableView.mj_header beginRefreshing];
    
    
    // 加载本地缓存中的空间内容---如果缓存中没有用户就手动刷新--一刷新完就会自动缓存内容到本地
//    [self getSpaceFromCache];
    
    
    
    self.title = @"动态";
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 进入刷新
    [self.tableView.mj_header beginRefreshing];
}

// 加载本地缓存中的空间内容
- (void)getSpaceFromCache
{
    NSArray *spaceFrame = [CRDataTool getSpaceFromCache];
    _spaceFrames = spaceFrame;
    // 刷新tableview
    [self.tableView reloadData];
    
}
// 添加刷新控件
- (void)addRefresh
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(fresh)];
    self.tableView.mj_header = header;
}


// 下拉刷新的方法
- (void)fresh
{
    // 获取当前用户的所有动态
    [self getAllSpace];
  
}

// 获取当前用户的所有动态
- (void)getAllSpace
{
    
    [CRTool getAllSpaceContentWithBlock:^(NSArray *data) {
       
        NSMutableArray *temp = [NSMutableArray array];
        for (AVObject *obj in data) {
            CRSpaceFrame *frame = [[CRSpaceFrame alloc] init];
            CRSpace *space = [CRSpace spaceWithAvobject:obj];
            frame.space = space;
            [temp addObject:frame];
            
        }
        _spaceFrames = temp;
        // 刷新tableview
        [self.tableView reloadData];
        // 停止刷新
        [self.tableView.mj_header endRefreshing];


    }];

}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.spaceFrames.count;
}

// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CRSpaceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    // 设置cell底部view(放着赞 分享等控件)的代理
//    cell.bottomView.delegate = self;
    
    // 设置cell底部view(放着赞 分享等控件)--tag 用来确定模型的位置
    cell.bottomView.praiseButton.tag = indexPath.row;
    cell.bottomView.noPraiseButton.tag = indexPath.row;
    cell.bottomView.shareButton.tag = indexPath.row;
    // 设置监听事件
    [cell.bottomView.praiseButton addTarget:self action:@selector(clickpraiseButton:) forControlEvents:UIControlEventTouchUpInside];
    [cell.bottomView.noPraiseButton addTarget:self action:@selector(clicknoPraiseButton:) forControlEvents:UIControlEventTouchUpInside];
    [cell.bottomView.shareButton addTarget:self action:@selector(clickshareButton:) forControlEvents:UIControlEventTouchUpInside];

    CRSpaceFrame *spaceFrame = self.spaceFrames[indexPath.row];

    cell.spaceFrame = spaceFrame;
    
    
    return cell;
}


// 点击了cell跳转到评论的控制器
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CRSpaceFrame *frameModel = self.spaceFrames[indexPath.row];
    // 给写评论的控制器传递一个模型，用于显示动态内容
    CRSpaceCommentViewController *VC = [[CRSpaceCommentViewController alloc] init];
    VC.frameModel = frameModel;
    VC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:VC animated:NO];
}

// 返回头部view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CRSpaceHeadView *headerView = [[CRSpaceHeadView alloc] init];

    // 设置textView的代理
    headerView.inputText.delegate = self;

    // 设置头部view代理
    headerView.delegate = self;

    return headerView;
    
}

// headerView的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

        return 30;

}


// 每个cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CRSpaceFrame *spaceFrame = self.spaceFrames[indexPath.row];
    return spaceFrame.cellHeight;
}

// 输入框的代理方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self spaceHeadViewDidClickSendButton:nil andSendText:nil];
}


#pragma mark 头部view中的发送按钮的代理方法
- (void)spaceHeadViewDidClickSendButton:(UIButton *)button andSendText:(NSString *)text
{
    [self.view endEditing:YES];
    // 调到写说说的控制器
    CRWriteViewController *writeVC = [[CRWriteViewController alloc] init];
    writeVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:writeVC animated:NO];

}


#pragma mark --- 滚动的时候退出键盘
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    
}


#warning 待优化===============================(KVO?)
#pragma mari - 点击赞按钮的方法
- (void)clickpraiseButton:(UIButton *)button
{
    // 拿到对应位置的模型
    CRSpaceFrame *spaceFrame = self.spaceFrames[button.tag];
    CRSpace *space = spaceFrame.space;
    NSMutableArray *muArray = [NSMutableArray array];
    if (space.praiseInfo == nil) {
        // 让数值++之后交给KVO处理。
        space.likeCount = space.likeCount + 1;
        int count = space.likeCount;
        // 添加赞的人username
        [muArray addObject:[AVUser currentUser].username];
        space.praiseInfo = muArray;
        
        [self.tableView reloadData];
        
        AVQuery *query = [AVQuery queryWithClassName:@"Post"];
        [query whereKey:@"objectId" equalTo:space.objectId];
        [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            [object setObject:@(count) forKey:@"likeCount"];
            [object setObject:muArray forKey:@"praiseInfo"];
            [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                NSLog(@"%@", error);
            }];
            
        }];
        
    } else if (![space.praiseInfo containsObject:[AVUser currentUser].username]) {
          // 如果没有点赞 需要处理
        // 让数值++之后交给KVO处理。
        space.likeCount = space.likeCount + 1;
        int count = space.likeCount;
        // 添加赞的人username
        muArray = (NSMutableArray *)space.praiseInfo;
        [muArray addObject:[AVUser currentUser].username];
         space.praiseInfo = muArray;
        
        [self.tableView reloadData];
        
        AVQuery *query = [AVQuery queryWithClassName:@"Post"];
        [query whereKey:@"objectId" equalTo:space.objectId];
        [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            [object setObject:@(count) forKey:@"likeCount"];
            [object setObject:muArray forKey:@"praiseInfo"];
            [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                NSLog(@"%@", error);

            }];
            
        }];
    
    } else {
        [MBProgressHUD showSuccess:@"已经赞过了奥"];
    }
    
//    // 刷新对应的单元格
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
//    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    

    
}
#pragma mari - 点击不赞按钮的方法
- (void)clicknoPraiseButton:(UIButton *)button
{

    // 拿到对应位置的模型
    CRSpaceFrame *spaceFrame = self.spaceFrames[button.tag];
    CRSpace *space = spaceFrame.space;
    NSMutableArray *muArray = [NSMutableArray array];
    
    if (!space.praiseInfo || ![space.praiseInfo containsObject:[AVUser currentUser].username]) {
        // 还没有赞的人
        [MBProgressHUD showError:@"您还没有赞过呢"];
        
    } else if ([space.praiseInfo containsObject:[AVUser currentUser].username]) { // 已经赞过了之后的处理

        space.likeCount = space.likeCount - 1;
        space.noLickCount = space.noLickCount + 1;
        // 添加赞的人username
        muArray = (NSMutableArray *)space.praiseInfo;
        [muArray removeObject:[AVUser currentUser].username];
        space.praiseInfo = muArray;
        
        [self.tableView reloadData];
        
        AVQuery *query = [AVQuery queryWithClassName:@"Post"];
        [query whereKey:@"objectId" equalTo:space.objectId];
        [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            [object setObject:@(space.likeCount) forKey:@"likeCount"];
            [object setObject:@(space.noLickCount) forKey:@"noLickCount"];
            [object setObject:muArray forKey:@"praiseInfo"];
            [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                NSLog(@"%@", error);
                
            }];
            
        }];
        
    } else {
        [MBProgressHUD showSuccess:@"已经赞过了奥"];
    }



}

#pragma mari - 点击分享按钮的方法
- (void)clickshareButton:(UIButton *)button
{

    // 拿到对应位置的模型
    CRSpaceFrame *spaceFrame = self.spaceFrames[button.tag];
    CRSpace *space = spaceFrame.space;
    space.shareCount = space.shareCount + 1;
    
    [self.tableView reloadData];
    
    AVQuery *query = [AVQuery queryWithClassName:@"Post"];
    [query whereKey:@"objectId" equalTo:space.objectId];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        [object setObject:@(space.shareCount) forKey:@"shareCount"];
        [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            [MBProgressHUD showSuccess:@"谢谢分享"];
        }];
        
    }];


    




}
@end















